<!--
  * 全景图时间筛选表单
  *
  * @Author:    骆伟林
  * @Date:      2025-10-22 17:09:49
  * @Copyright  软件需求工程第八组
-->
<template>
  <a-modal :title="'全景图时间选择'" :open="visibleFlag" @cancel="onClose" :maskClosable="false" :destroyOnClose="true">
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 5 }" class="smart-query-form">
      <a-row class="smart-query-form-row">
        <a-col :span="24">
          <a-form-item label="日期" name="pictureTime">
            <a-date-picker
              show-time
              valueFormat="YYYY-MM-DD HH:mm:ss"
              v-model:value="form.pictureTime"
              style="width: 100%"
              placeholder="拍摄日期"
              :disabledDate="disabledDate"
              :disabledTime="disabledTime"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">跳转</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
  import { reactive, ref, nextTick, onMounted, onUnmounted } from 'vue';
  import _ from 'lodash';
  import dayjs from 'dayjs';
  import { useRoute, useRouter } from 'vue-router';
  const router = useRouter();
  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['reloadList']);

  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const visibleFlag = ref(false);

  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref();

  const formDefault = {
    pictureTime: undefined,
    picture: undefined,
  };

  let form = reactive({ ...formDefault });

  const rules = {
    pictureTime: [{ required: true, message: '全景图拍摄日期 必填' }],
  };

  const pictureList = ref([]);
  const isInitialized = ref(false);
  function show(rowData) {
    console.log(rowData);
    pictureList.value = rowData;

    // 初始化表单
    Object.assign(form, formDefault);

    if (!rowData || _.isEmpty(rowData)) {
      console.warn('rowData 为空，无法设置时间限制');
      visibleFlag.value = true;
      nextTick(() => {
        formRef.value.clearValidate();
      });
      return;
    }

    // 按日期分组时间点
    const groupedData = rowData.reduce((acc, item) => {
      const [date, time] = item.pictureTime.split(' ');
      const timeParts = time.split(':');
      const formattedTime = `${timeParts[0]}:${timeParts[1] || '00'}:${timeParts[2] || '00'}`; // 补全分秒
      if (!acc[date]) acc[date] = new Set();
      acc[date].add(formattedTime);
      return acc;
    }, {});

    // 设置日期和时间限制
    disabledDates.value = new Set(Object.keys(groupedData));
    disabledTimes.value = groupedData;

    // 默认选择最晚日期和时间
    const defaultDate = Array.from(disabledDates.value).sort().pop();
    if (defaultDate && disabledTimes.value[defaultDate]) {
      const availableTimes = Array.from(disabledTimes.value[defaultDate]).sort((a, b) => {
        const timeA = new Date(`1970-01-01 ${a}`).getTime();
        const timeB = new Date(`1970-01-01 ${b}`).getTime();
        return timeA - timeB;
      });
      const lastTime = availableTimes.pop();
      form.pictureTime = `${defaultDate} ${lastTime}`;
    }
    visibleFlag.value = true;
    nextTick(() => {
      formRef.value.clearValidate();
    });
  }
  // 可用日期集合
  const disabledDates = ref(new Set());

  // 可用时间集合
  const disabledTimes = ref({});
  // 禁用日期
  function disabledDate(currentDate) {
    return !disabledDates.value.has(currentDate.format('YYYY-MM-DD'));
  }

  function disabledTime(selectedDate) {
    if (!selectedDate) {
      // 初始化时禁用所有时间选择
      return {
        disabledHours: () => Array.from(new Set(Array(24).keys())),
        disabledMinutes: () => Array.from(new Set(Array(60).keys())),
        disabledSeconds: () => Array.from(new Set(Array(60).keys())),
      };
    }

    const dateKey = selectedDate.format('YYYY-MM-DD');
    if (!disabledTimes.value[dateKey]) return {};

    const availableTimes = Array.from(disabledTimes.value[dateKey]);

    return {
      disabledHours: () => {
        const hours = availableTimes.map((time) => parseInt(time.split(':')[0]));
        return Array.from(new Set(Array(24).keys())).filter((hour) => !hours.includes(hour));
      },
      disabledMinutes: (selectedHour) => {
        const minutes = availableTimes.filter((time) => parseInt(time.split(':')[0]) === selectedHour).map((time) => parseInt(time.split(':')[1]));
        return Array.from(new Set(Array(60).keys())).filter((minute) => !minutes.includes(minute));
      },
      disabledSeconds: (selectedHour, selectedMinute) => {
        const seconds = availableTimes
          .filter((time) => parseInt(time.split(':')[0]) === selectedHour && parseInt(time.split(':')[1]) === selectedMinute)
          .map((time) => parseInt(time.split(':')[2]));
        return Array.from(new Set(Array(60).keys())).filter((second) => !seconds.includes(second));
      },
    };
  }

  function onClose() {
    Object.assign(form, formDefault);
    visibleFlag.value = false;
  }

  function onSubmit() {
    const picture = pictureList.value.find((item) => item.pictureTime === form.pictureTime);
    const pictureUrl = picture?.pictureUrl[0]?.fileUrl;
    console.log(picture);
    if (!pictureUrl) {
      console.warn('未找到有效的图片URL');
      return;
    }
    router.push({
      path: '/panorama',
      query: {
        addressId: picture.addressId,
        pictureTime: form.pictureTime,
        pictureUrl: pictureUrl,
        pictureName: picture.pictureName,
      },
    });
  }

  onUnmounted(() => {
    formRef.value = null;
  });
  function initializeOnce() {
    if (isInitialized.value) return;
    isInitialized.value = true;
  }
  onMounted(() => {
    initializeOnce();
  });

  defineExpose({
    show,
  });
</script>
